package com.dky.satell.kafka.consumer.file;

import cn.hutool.core.collection.CollectionUtil;
import com.dky.satell.entity.LocalTask;
import com.dky.satell.mapper.LocalTaskMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;

/**
 * @ClassName FileDownloader
 * @Description
 * @Author superz
 * @Date 2021/4/28 9:49
 * @Version 1.0
 **/
@Slf4j
@Component
public class FileDownloader {

    public static final String FILE_DOWNLOAD_TYPE = "file_download";

    /**
     * 下载本地路径
     */
    @Value("${file.downloadPath}")
    private String downloadPath;

    @Resource
    private LocalTaskMapper localTaskMapper;

    /**
     * 由30s推送，无须手动同步
     */
//    @Scheduled(cron = "0 */5 * * * ?")
    public void scheduled() {
        List<LocalTask> taskList = localTaskMapper.queryFileTasks(FILE_DOWNLOAD_TYPE);
        if (CollectionUtil.isNotEmpty(taskList)) {
            for (LocalTask task : taskList) {
                log.info("下载文件: {}", task.getContent());
                // 处理中
                localTaskMapper.updateStatus(task.getId(), (byte) 1);

                String proxyFileName = task.getContent();
                try {
                    File proxyFile = new File(downloadPath + proxyFileName);
                    File downloadFile = new File(downloadPath + proxyFileName);
                    FileUtils.copyFile(proxyFile,downloadFile);
                    localTaskMapper.updateStatusAndTimes(task.getId(), (byte) 3);
                } catch (Exception e) {
                    if (e.getMessage().equals("Server response error with status code: [404]")) {
                        // 文件还没传输到位
                        log.error("文件不存在: " + proxyFileName);
                        // 失败
                        localTaskMapper.updateStatusAndTimes(task.getId(), (byte) 2);
                    }
                }
            }
        }
    }
}
